package erp_services

import (
	"errors"
	"xiehui-service/app/common/request"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/app/services/types"
	"xiehui-service/global"

	"go.uber.org/zap"
)

type orderTaskService struct {
}

type QueryParams struct {
	ID           int64
	TaskStatus   []int64
	AutoDispatch int64
	VerifyStatus []int64
	ZlPtaskId    string
	PageNum      int64
	PageSize     int64
}

type OrderListResult struct {
	List         []erp_models.OrderTask
	TotalPages   int64
	TotalRecords int64
}

var OrderTaskService = new(orderTaskService)

// GetOrderTaskInfo 获取任务单信息
func (orderTaskService *orderTaskService) GetOrderTaskInfo(params request.List) (orderTask *erp_models.OrderTask, err error) {
	err = global.App.DB.First(&orderTask, params.Id).Error
	if err != nil {
		orderTask = nil
		err = errors.New("数据不存在")
	}
	return
}

func (orderTaskService *orderTaskService) GetOrderTaskByLine(taskId uint, lineNumber string) (orderTask *erp_models.OrderTask, err error) {
	err = global.App.DB.Where("id = ? AND line_number = ?", taskId, lineNumber).First(&orderTask).Error
	if err != nil {
		orderTask = nil
		err = errors.New("数据不存在")
	}
	return
}

func (orderTaskService *orderTaskService) GetOrderTaskByUnioNo(unionNo string) (orderTask erp_models.OrderTask, err error) {
	err = global.App.DB.Where("union_no = ? ", unionNo).Find(&orderTask).Error

	if err != nil {
		err = errors.New("数据不存在")
	}
	return
}

// 查询开启自动调度的任务单
func (orderTaskService *orderTaskService) GetAutoOrderTask() (orderTask []erp_models.OrderTask, err error) {
	err = global.App.DB.Find(&orderTask, "auto_dispatch = ? AND task_status = ?", 1, 3).Error
	if err != nil {
		err = errors.New("数据不存在")
	}
	return
}

// 设置订单自动调度状态
func (orderTaskService *orderTaskService) SetAutoDispatch(task_id uint, state uint) (orderTask erp_models.OrderTask, err error) {
	err = global.App.DB.Model(&orderTask).Where("id = ?", task_id).Updates(map[string]interface{}{"auto_dispatch": state}).Error
	if err != nil {
		err = errors.New("数据更新失败")
	}

	return
}

// 获取订单
func (orderTaskService *orderTaskService) OrderTaskList(params QueryParams, pagination types.Pagination) (result *OrderListResult, err error) {
	query := global.App.DB.Model(&erp_models.OrderTask{})
	if len(params.TaskStatus) > 0 {
		query = query.Where("task_status IN (?)", params.TaskStatus)
	}
	if len(params.VerifyStatus) > 0 {
		query = query.Where("verify_status IN (?)", params.VerifyStatus)
	}

	// 获取总记录数
	var totalRecords int64
	if err = query.Count(&totalRecords).Error; err != nil {
		return nil, err
	}

	// 设置分页查询条件
	offset := (pagination.PageNum - 1) * pagination.PageSize
	query = query.Order("ID DESC").Offset(int(offset)).Limit(int(pagination.PageSize))

	// 获取当前页记录数
	var currentOrderTasks []erp_models.OrderTask
	if err = query.Find(&currentOrderTasks).Error; err != nil {
		return nil, err
	}

	// 计算总页数
	totalPages := (totalRecords + int64(pagination.PageSize) - 1) / int64(pagination.PageSize)

	return &OrderListResult{
		List:         currentOrderTasks,
		TotalPages:   totalPages,
		TotalRecords: totalRecords,
	}, nil
}

// 新增任务单
func (orderTaskService *orderTaskService) Create(orderTask erp_models.OrderTask) (uint, error) {
	result := global.App.DB.Create(&orderTask)
	if result.Error != nil {
		return 0, result.Error
	}
	return orderTask.ID.ID, nil
}

func (orderTaskService *orderTaskService) Update(orderTask erp_models.OrderTask, autoUpTime bool) (err error) {
	omitsFields := []string{"id", "union_no", "created_at"}

	if !autoUpTime {
		omitsFields = append(omitsFields, "updated_at")
	}
	if err := global.App.DB.Model(&erp_models.OrderTask{}).Where("id = ?", orderTask.ID.ID).Omit(omitsFields...).Updates(&orderTask).Error; err != nil {
		return err
	}
	return nil
}

// 根据订单ID更新数据
func (orderTaskService *orderTaskService) SetById(task_id uint, fields map[string]interface{}) (err error) {
	var orderTask erp_models.OrderTask
	if err = global.App.DB.First(&orderTask, task_id).Error; err != nil {
		err = errors.New("未查询到订单信息")
		return
	}

	if err = global.App.DB.Model(&orderTask).Updates(fields).Error; err != nil {
		return
	}

	return nil
}

func (orderTaskService *orderTaskService) CloseAllDispatch() (orderTask []erp_models.OrderTask, err error) {
	err = global.App.DB.Model(&orderTask).Where("auto_dispatch = ?", 1).Updates(map[string]interface{}{"auto_dispatch": 0}).Error
	if err != nil {
		err = errors.New("数据更新失败")
	}

	return
}

// 设置暂停方量
func (orderTaskService *orderTaskService) SetPauseQuantity(task_id uint, pause_quantity float64) (orderTask erp_models.OrderTask, err error) {
	err = global.App.DB.Model(&orderTask).Where("id = ?", task_id).Updates(map[string]interface{}{"pause_quantity": pause_quantity}).Error
	if err != nil {
		err = errors.New("数据更新失败")
	}

	return
}

func (orderTaskService *orderTaskService) SetAutoRatio(task_id uint, auto_ratio int) (orderTask erp_models.OrderTask, err error) {
	err = global.App.DB.Model(&orderTask).Where("id = ?", task_id).Updates(map[string]interface{}{"auto_ratio": auto_ratio}).Error
	if err != nil {
		err = errors.New("数据更新失败")
	}

	return
}

// 查询指定时间之后更新的订单信息
func (orderTaskService *orderTaskService) OrderTasksByTime(lastTime string, num int64, line_number string) (taskOrders []erp_models.OrderTask, err error) {
	query := global.App.DB.Model(&erp_models.OrderTask{})
	query = query.Where("line_number = ? AND updated_at > ? AND verify_status = 3 AND task_status <> 10 AND deleted_at is null", line_number, lastTime).Order("id").Limit(int(num))

	if err = query.Find(&taskOrders).Error; err != nil {
		return nil, err
	}
	return
}

// 更新配合比
func (orderTaskService *orderTaskService) SetWorkMixtureNo(task_id uint, mixerNo string) (err error) {
	var orderTask erp_models.OrderTask
	err = global.App.DB.Model(&orderTask).Where("id = ?", task_id).Updates(map[string]interface{}{"work_mixture_no": mixerNo}).Error
	if err != nil {
		err = errors.New("数据更新失败")
	}

	return
}

func (orderTaskService *orderTaskService) GetOrderTaskByTaskNo(taskNo string, line_number string) (orderTask *erp_models.OrderTask, err error) {
	err = global.App.DB.Where("task_no = ?  AND line_number = ? ", taskNo, line_number).First(&orderTask).Error
	if err != nil {
		orderTask = nil
		err = errors.New("数据不存在")
	}
	return
}

// 获取产线的标准配比
func (orderTaskService *orderTaskService) GetMixer(machine_no string) (phb string) {
	var phbReq request.PhbRequest
	phbReq.CfgcGCID = "" //global.App.Config.App.Zdid

	res, err := LqApiService.HttpPhb(phbReq)
	if err != nil {
		return
	}

	for _, item := range res.Data.([]interface{}) {
		// log.Println("idx, item==>>", idx, item.(map[string]interface{})["INFO"], item.(map[string]interface{})["SCCJID"])
		if global.App.Config.App.CompanyId == item.(map[string]interface{})["SCCJID"] {
			phb, _ := item.(map[string]interface{})
			return phb["INFO"].(string)
		}
	}
	return
}

// 根据配比ID获取配合比
func (orderTaskService *orderTaskService) GetPhbById(PBID string) (phb map[string]interface{}) {
	var phbReq request.SccjPhbRequest
	phbReq.SCCJID = global.App.Config.App.Zdid

	res, err := LqApiService.HttpSccjPhb(phbReq)
	if err != nil {
		global.App.Log.Error("【GetPhbById】获取路桥生产厂家配比接口失败:", zap.Any("原因", err.Error()))
		return
	}
	mList := make(map[string]interface{})
	for _, item := range res.Data.([]interface{}) {
		itemMap := item.(map[string]interface{})
		valueMap := make(map[string]interface{})

		if PBID == item.(map[string]interface{})["ID"] {
			valueMap["MXWZBH"] = itemMap["MXWZBH"] // 物资编号
			valueMap["MXWZMC"] = itemMap["MXWZMC"] // 物质名称
			valueMap["MXJLDW"] = itemMap["MXJLDW"] // 计量单位
			valueMap["MXGGXH"] = itemMap["MXGGXH"] // 规格型号
			valueMap["BL"] = itemMap["BL"]         // 理论设定值

			mList[itemMap["MXWZBH"].(string)] = valueMap
		}
	}
	return mList
}
